//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/api/rest/ActionResource.java $
//$Id: ActionResource.java 127 2013-04-07 20:43:54Z krieg.maria@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.api.rest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.piratech.dasding.data.Action;
import de.piratech.dasding.data.ActionCategory;
import de.piratech.dasding.data.Event;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.security.annotations.RequireUserRole;
import de.piratech.dasding.services.Geocoder;
import de.piratech.dasding.services.LocationFilter;

/**
 * Resource for public action requests
 * <p>
 * Those include:
 * <p>
 * GET: find actionsn<br>
 * PUT: -<br>
 * POST: create an action<br>
 * DELETE: -<br>
 * <p>
 * 
 * @author deveth0
 */
@Path("/actions")
@Component
public class ActionResource extends AbstractResource {

  private static final Logger LOG = LoggerFactory
      .getLogger(ActionResource.class);

  @Autowired
  LocationFilter locationFilter;

  @Autowired
  private Geocoder geocoder;

  /**
   * Returns actions by coordinates, distance and categories
   * 
   * http://localhost:8080/dasding.api/api/actions
   * http://localhost:8080/dasding.
   * api/api/actions?lat=10.21&lon=52.123&distance=2.3
   * http://localhost:8080/dasding.api/api/actions?category=cat1&category=cat2
   * 
   * GET
   * 
   * @param pLatitude
   * @param pLongitude
   * @param pDistance
   * @param pCategory
   * @return
   */
  @GET
  @Path("/find")
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public List<Action> findActions(@QueryParam(value = "lat") Float pLatitude,
      @QueryParam(value = "lon") Float pLongitude,
      @QueryParam(value = "distance") Float pDistance,
      @QueryParam(value = "category") List<String> pCategory) {
    LOG.debug("findActions(lat={}, lon={}, distance={}, category={})",
        pLatitude, pLongitude, pDistance, pCategory);
    try {
      List<Action> findByCategories = null;
      if (pCategory != null && pCategory.size() > 0) {
        findByCategories = getActionData().findActionsByCategories(pCategory);
      } else {
        findByCategories = getActionData().getActions();
      }

      if (pLongitude != null && pLongitude != null) {
        if (pDistance <= 0) {
          throw getBadRequestException("distance cannot be less than or equal null");
        } else {
          List<Action> actionsInArea = locationFilter.getEventsInArea(
              findByCategories, pLatitude, pLongitude, pDistance);
          return actionsInArea == null ? new ArrayList<Action>()
              : actionsInArea;
        }
      } else {
        return findByCategories;
      }
    } catch (DatabaseException dbe) {
      throw getBadRequestException(dbe);
    }
  }

  /**
   * Creates a new action
   * 
   * http://localhost:8080/dasding.api/api/actions
   * 
   * POST
   * 
   * @param pName
   *          (required)
   * @param pDescription
   *          (required)
   * @param pCategoryID
   *          (required)
   * @param pTime
   *          (required)
   * @param pLatitude
   *          (required)
   * @param pLongitude
   *          (required)
   * @param pEventId
   *          (required)
   * @return
   */
  @POST
  @RequireUserRole(roles = User.USER_ROLE.USER)
  public Response createAction(@FormParam("name") String pName,
      @FormParam("description") String pDescription,
      @FormParam("categoryid") String pCategoryID,
      @FormParam("time") String pTime, @FormParam("latitude") Double pLatitude,
      @FormParam("longitude") Double pLongitude,
      @FormParam("locationid") String pLocationId,
      @FormParam("eventid") String pEventId,
      @Context SecurityContext pSecurityContext) {
    LOG.debug(
        "createEvent(name={}, description={}, categoryId={}, time={}, latitude={}, longitude={}, eventid={})",
        pName, pDescription, pCategoryID, pTime, pLatitude, pLongitude,
        pEventId);
    try {
      Event event = getEventData().getEvent(pEventId);
      User user = getUserFromSecurityContext(pSecurityContext);
      if (event == null) {
        return getBadRequestResponse("Event does not exist");
      }
      if (!StringUtils.equals(user.getId(), event.getResponsible().getId())) {
        return getForbiddenResponse("Wrong user");
      }
      Action action = new Action();
      action.setName(pName);
      action.setDescription(pDescription);
      action.setContact(user);
      action.setResponsible(user);
      action.setCategory(getCategory(pCategoryID));
      action.setStatus(Action.ACTIONSTATUS.REQUIRES_PARTICIPANTS);
      action.setEvent(event);
      try {
        // TODO made pattern configurable
        // TODO regulate how time is send to client
        // TODO handle timezone
        action
            .setTime(new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'+02:00'")
                .parse(pTime));
      } catch (ParseException e) {
        return getBadRequestResponse(e);
      }
      if (StringUtils.isNotEmpty(pLocationId)) {
        action.setLocation(getLocationData().getLocation(pLocationId));
      } else {
        action.setLocation(geocoder.resolve(pLongitude, pLatitude));
      }
      if (!action.isValid()) {
        return getBadRequestResponse();
      }
      Action newAction = getActionData().createAction(action);
      // TODO move this to add action method in database layer?
      event.addAction(newAction);
      getEventData().updateEvent(event);
      return getCreatedResponse("/id/" + action.getId());
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  private ActionCategory getCategory(String pCategoryID)
      throws DatabaseException {
    return getActionCategoryData().getActionCategory(pCategoryID);

  }

  @Override
  protected Logger getLogger() {
    return LOG;
  }
}
